<template>
  <div class="mini-tree-box">
    <ag-popup
      v-model="visible"
      title="个人图层"
      @onCancel="onCancel"
      class="popup-box"
      ref="miniTreePage"
      @contextmenu.prevent
    >
      <div class="content">
        <div class="top-box">
          <layer-tree-list
            :allKeys="allKeys"
            @appendLayer="appendLayer"
            ref="lyListBox"
          ></layer-tree-list>
          <!-- left start -->
          <div class="left">
            <div class="t-title">
              <span class="t4">我的图层树</span>
              <div @click="appendFolder('root')">
                <i class="icon-add-folder"></i>
              </div>
            </div>
            <!-- ag-scrollbar start -->
            <div class="ag-scrollbar">
              <el-tree
                highlight-current
                show-checkbox
                :data="data"
                node-key="id"
                default-expand-all
                :default-checked-keys="defaultCheckedKeys"
                :expand-on-click-node="false"
                ref="miniTreeBox"
                :draggable="draggable"
                :allow-drop="allowDrop"
                @node-click="openAddLayer"
                @node-contextmenu="openTreeContextMenu"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span v-if="data.id != curSelectData.id || !isRenaming" :title="node.label">
                    <i v-if="data.children" class="icon-folder"></i>
                    <i v-if="!data.children" class="icon-list"></i>
                    {{ node.label }}
                    <i
                      class="icon-more"
                      @click="openTreeContextMenu($event, data, node)"
                    ></i>
                  </span>

                  <span v-if="data.id === curSelectData.id && isRenaming">
                    <input
                      class="rename"
                      type="text"
                      v-model.trim="curSelectData.label"
                      ref="rename"
                      @focus="focus($event)"
                      @blur="submitRename()"
                      @keyup.enter="submitRename()"
                    />
                  </span>
                </span>
              </el-tree>
            </div>
            <!-- ag-scrollbar end -->
          </div>
          <!-- left end -->
        </div>
        <div class="btm-box">
          <el-button class="clearcss" plain size="small" @click="onCancel">
            取消
          </el-button>
          <el-button type="primary" size="small" @click="saveTree">
            保存
          </el-button>
        </div>
      </div>
    </ag-popup>

    <!-- 右键菜单 rt-menu-box start-->
    <div
      class="rt-menu-box"
      ref="rtMenuBox"
      v-show="isRtMenuShow"
      @mouseleave="hideTreeContextMenu"
    >
      <ul v-show="rtMenuObj.hasChild">
        <li @click="appendFolder()">
          <span>新建文件夹</span>
        </li>
        <li @click="rename()">
          <span>重命名</span>
        </li>
        <li>
          <span @click="removeNode">删除</span>
        </li>
      </ul>
      <ul v-show="!rtMenuObj.hasChild">
        <li>
          <span @click="removeNode">删除</span>
        </li>
      </ul>
    </div>
    <!-- 右键菜单 rt-menu-box end-->
  </div>
</template>
<script>
import AgPopup from "@/views/components/precut/AgPopup.vue";
import serverData from "@/views/js/api/imageDataApi";
import dirImageDataApi from "@/views/js/api/dirImageDataApi";
import layerTreeList from "./layerTreeList.vue";
export default {
  components: {
    "ag-popup": AgPopup,
    "layer-tree-list": layerTreeList,
  },
  data() {
    return {
      visible: true,
      //展示的树
      data: [],
      //当前树id
      curId: "",
      //默认选中
      defaultCheckedKeys: [],
      //拖拽
      draggable: true,
      //图层ids--------根据dirLayerId过滤
      allKeys: [],
      //右键菜单是否显示
      isRtMenuShow: false,
      //右键菜单
      rtMenuObj: {
        hasChild: false,
        list: [
          {
            index: "0",
            name: "删除",
            key: "removeNode",
            state: true,
          },
        ],
      },
      //右键当前选中的node
      curSelectNode: "",
      curSelectData: "",
      //重命名状态
      isRenaming: false,
      dirId: null,
    };
  },
  mounted() {
    this.getTreeData();
  },
  methods: {
    async getTreeData() {
      let vm = this;
      let code = { code: "other-AgCIM-LayerTreeMini" };
      let response = await dirImageDataApi.treeByCode(code);
      if (response.success && response.content.length > 0) {
        vm.dirId = response.content[0].imageStoreDirId;
      }
      let params = {
        dirCode: "other-AgCIM-LayerTreeMini",
        page: 1,
        rows: 1000,
      };
      let res = await serverData.selectAuthPageByDirCode(params);
      this.data = [];
      if (res.success ) {
        let arr = this.apiFieldConvert(res.content.list);
        if (arr.length) {
          arr.forEach(item=>{
            if (item.imageStoreName == this.$store.state.projectName){
              let o = JSON.parse(item.information);
              this.data = o.data;
              if (o.defaultCheck) {
                this.defaultCheckedKeys = o.defaultCheck.split(",");
              }
              this.curId = item.id;
              this.allKeys = this.getMenuKeys(this.data, []);
              this.curSelectData = "";
              this.curSelectNode = "";
            }
            
          })
          
        }
      }
    },
    //将接口字段替换成当前使用的字段
    apiFieldConvert(list){
      let listConvert = [];
      list.forEach(ele => {
        let item = {
          ...ele,
          dirId: ele.imageStoreDirId,
          id: ele.imageStoreId,
          name: ele.imageStoreDirName,
          information: ele.imageStoreInformation,
        }
        listConvert.push(item)
      });
      return listConvert;
    },
    //隐藏右键的菜单
    hideTreeContextMenu: function (e) {
      this.isRtMenuShow = false;
    },
    //右键+点击 兼容
    openTreeContextMenu(event, data, node) {
      this.curSelectNode = node;
      this.curSelectData = data;
      this.isRtMenuShow = true;
      this.$nextTick(() => {
        let l = event.clientX;
        let t = event.clientY;
        this.$refs.rtMenuBox.style.left = l + "px";
        this.$refs.rtMenuBox.style.top = t + "px";
        if (this.curSelectData.children) {
          this.rtMenuObj.hasChild = true;
        } else {
          this.rtMenuObj.hasChild = false;
        }
      });
    },
    //添加文件夹
    appendFolder(root) {
      const newChild = {
        id: this.guid(10),
        label: "新建文件夹",
        children: [],
      };

      if ("root" == root) {
        this.data.push(newChild);
      } else {
        let data = this.curSelectNode.data;
        if (!data.children) {
          this.$set(data, "children", []);
        }
        data.children.push(newChild);
      }
    },
    async save() {

      let defaultCheck = this.$refs.miniTreeBox.getCheckedKeys().toString();
      let params  = {
        id: this.curId,
        name: this.$store.state.projectName,
        userId: CIM_USER_ID,
        dirId: this.dirId,
        information: JSON.stringify({
          data: this.data,
          defaultCheck: defaultCheck,
        }),
      };
      //将当前字段替换为接口字段
      let apiFieldList = {
        imageStoreId: params.id,
        imageStoreName:params.name,
        imageStoreDirId:params.dirId,
        imageStoreInformation:params.information
      }
      let res = await serverData.saveImageStore(apiFieldList);
      if (res.success) {
        this.$message.success(res.message);
        this.getTreeData();
        this.curId = res.content;
        this.$store.state.layerTreeMiniState = true;
      }
    },
    async update(option) {
      let defaultCheck = this.$refs.miniTreeBox.getCheckedKeys().toString();
      let params =  {
        id: this.curId,
        dirId: this.dirId,
        information: JSON.stringify({
          data: this.data,
          defaultCheck: defaultCheck,
        }),
      };
      //将当前字段替换为接口字段
      let apiFieldList = {
        imageStoreId: params.id,
        imageStoreDirId:params.dirId,
        imageStoreInformation:params.information
      }
      let res = await serverData.updateImageStore(apiFieldList);
      this.isRtMenuShow = false;
      if (res.success) {
        this.getTreeData();
        this.$store.state.layerTreeMiniState = true;
      }
    },
    //保存默认图层
    saveTree() {
      if (this.curId) {
        this.update();
      } else {
        this.save();
      }

      this.onCancel()
    },
    //重命名
    rename() {
      this.isRenaming = true;
      this.draggable = false;
      this.$nextTick(() => {
        this.$refs.rename.focus();
        this.isRtMenuShow = false;
      });
    },
    focus(event) {
      event.currentTarget.select();
    },
    //确定重命名
    submitRename() {
      if (!this.curSelectNode.data.label) {
        return this.$message.warning("请输入名称");
      }
      this.update();
      this.isRenaming = false;
      this.draggable = true;
    },
    //删除
    removeNode() {
      let node = this.curSelectNode;
      let data = this.curSelectData;

      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);

      this.allKeys = this.getMenuKeys(this.data, []);
      this.$refs.lyListBox.setCheckedKeys(this.allKeys);
      this.curSelectData = "";
      this.curSelectNode = "";
      // this.update();
    },
    //选中添加图层的节点
    openAddLayer(data, node, node1) {
      this.curSelectNode = node;
      this.curSelectData = data;
    },
    //移除添加图层
    appendLayer(obj) {
      let vm = this;
      let o = obj.data;

      if (obj.state && o && o.id) {
        //过滤是否已存在
        let nodeExist = this.$refs.miniTreeBox.getNode(o.id);
        if (nodeExist && nodeExist.data) {
          return;
        }

        let newChild = {
          id: o.id,
          label: o.text,
          dirLayerId: o.dirLayerId,
        };
        let node = this.curSelectNode;
        let data = this.curSelectData;
        //根目录
        if (!data) {
          this.data.push(newChild);
        } else {
          //非文件夹
          if (data.dirLayerId) {
            if (node.parent.data instanceof Array) {
              //根
              node.parent.data.push(newChild);
            } else {
              let p = node.parent.data.children; //当前图层后面加
              let index = p.indexOf(node.data) + 1;
              p.splice(index, 0, newChild);
            }
          } else {
            //文件夹
            data.children.push(newChild);
          }
        }
      } else {
        //在整棵树里面找，然后移除
        this.$refs.miniTreeBox.remove(obj.data);
      }
    },

    getMenuKeys(tree, arr) {
      for (let value of tree) {
        if (value.dirLayerId) {
          arr.push(value.id);
        }
        if (value.children) {
          this.getMenuKeys(value.children, arr);
        }
      }
      return arr;
    },
    guid(len) {
      return Number(
        Math.random().toString().substr(3, len) + Date.now()
      ).toString(36);
    },
    onShow() {
      this.visible = true;
    },
    onCancel() {
      this.visible = false;
      this.$emit("close", {
        code: "LayerTreeMini",
      });
    },
    //限制图层放图层
    allowDrop(draggingNode, dropNode, type) {
      if (dropNode.data.dirLayerId) {
        return type !== "inner";
      } else {
        return true;
      }
    },
  },
};
</script>
<style scoped>
.popup-box {
  width: 700px;
  top: 135px;
  left: 620px;
  z-index: 366;
}

.popup-box .left {
  flex: 1;
}

.popup-box .top-box {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #919499;
}

.popup-box .top-box .el-select {
  width: 120px;
  margin-right: 10px;
}

.popup-box .t-title {
  display: flex;
  justify-content: space-between;
  color: #fff;
  line-height: 36px;
  padding: 10px 16px 0;
}

.popup-box .t-title div {
  color: #409eff;
  cursor: pointer;
}

.btm-box {
  padding: 20px;
  text-align: right;
}

.btm-box .el-button {
  width: 88px;
}

.icon-add-folder {
  display: inline-block;
  width: 30px;
  height: 30px;
  background: url(./img/icon-add-folder.png) no-repeat;
  background-size: 100%;
  margin-right: 2px;
  vertical-align: middle;
}

.icon-folder {
  display: inline-block;
  width: 14px;
  height: 14px;
  background: url(./img/icon-folder.png) no-repeat;
  background-size: 100%;
  margin-right: 2px;
  vertical-align: text-bottom;
}

.icon-list {
  display: inline-block;
  width: 14px;
  height: 14px;
  background: url(./img/icon-list.png) no-repeat;
  background-size: 100%;
  margin-right: 2px;
  vertical-align: text-bottom;
}

.mini-tree-box {
  position: relative;
}

.mini-tree-box .ag-scrollbar {
  min-height: 200px;
  max-height: 400px;
  overflow-x: hidden;
  overflow-y: scroll;
}

.mini-tree-box .rename {
  width: 120px;
  outline: none;
  border: 1px solid #409eff;
  color: #666;
}

.mini-tree-box .el-input {
  height: 28px;
  width: 120px;
  margin-right: 10px;
}

.el-tree .icon-more {
  display: none;
  position: absolute;
  right: 20px;
  width: 28px;
  height: 28px;
  background: url(./img/icon-more.png) no-repeat;
  background-size: 50%;
}

.el-tree-node__content:hover .icon-more {
  display: inline-block;
}

/* 菜单树右侧鼠标菜单 */
.rt-menu-box {
  position: fixed;
  z-index: 367;
  width: 124px;
  padding: 0 0 6px;
  background-color: rgba(1, 10, 23, 0.8);
  -webkit-box-shadow: 0px 1px 15px 1px rgba(69, 65, 78, 0.18);
  box-shadow: 0px 1px 15px 1px rgba(69, 65, 78, 0.18);
  border-radius: 4px;
}

.rt-menu-box ul {
  padding: 0;
  margin: 0;
}

.rt-menu-box li {
  list-style-type: none;
  padding-top: 6px;
}

.rt-menu-box span {
  display: block;
  color: #fff;
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  border: 0px;
  border-radius: 1px;
  text-indent: 20px;
}

.rt-menu-box span:hover {
  color: #fff;
  background: #1e90ff;
  cursor: pointer;
}

.rt-menu-box span i {
  margin-right: 10px;
}

.el-tree {
  position: relative;
  cursor: default;
  background: transparent;
  color: #fff;
  padding-left: 10px;
}

::v-deep .el-checkbox__inner {
  background-color: transparent;
}

.mini-tree-box ::v-deep.el-tree-node__content {
  position: relative;
  height: 32px;
  font-size: 14px;
}

.mini-tree-box ::v-deep.el-tree-node .el-tree-node__content:hover {
  background: rgba(255, 255, 255, 0.2);
}

.mini-tree-box ::v-deep.el-tree-node:focus > .el-tree-node__content {
  background: rgba(255, 255, 255, 0.2);
}

::v-deep.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background: rgba(255, 255, 255, 0.2);
}

.custom-tree-node{
  width: 220px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>